/*
 * Copyright 2010 Chad Retz
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.jdocng.parse;

import java.io.File;
import java.io.IOException;
import java.util.ServiceLoader;

import org.jdocng.log.LoggerFactory;
import org.jdocng.log.LoggerNotFoundException;
import org.jdocng.shared.Configuration;
import org.jdocng.shared.JavadocNgRuntimeException;
import org.jdocng.shared.context.Context;

/**
 * Factory to load the parser. It first attempts to use
 * {@link Configuration#getParser()} and attempts to load it
 * as a qualified class name. If not present, all {@link ServiceLoader}
 * references to {@link Parser} compare the configuration
 * value with {@link Parser#getShortName()}. Otherwise, just
 * the first SPI class is used. The default in this distribution is
 * {@link org.jdocng.parse.qdox.QDoxParser}.
 *
 * @author Chad Retz
 */
public class ParserFactory {

    private static ServiceLoader<Parser> parserLoader = ServiceLoader.load(Parser.class);
    
    /**
     * Build a parser with the given configuration. Reference
     * the class comments for more information
     * 
     * @param configuration
     * @return
     * @throws ParserNotFoundException
     */
    public static Parser buildParser(Configuration configuration)
            throws ParserNotFoundException {
        //not there? load first from service loader
        if (configuration.getParser() == null) {
            for (Parser parser : parserLoader) {
                return parser;
            }
            throw new ParserNotFoundException(
                    "Unable to find suitable parser");
        }
        //try what was passed in
        try {
            return (Parser) Class.forName(configuration.getParser()).newInstance();
        } catch (Exception e) {
            //welp, just try short name
            for (Parser parser : parserLoader) {
                if (configuration.getParser().equals(parser.getShortName())) {
                    return parser;
                }
            }
            //error
            throw new ParserNotFoundException("Class name and/or short name '" +
                    configuration.getParser() + "' not found or couldn't be loaded", e);
        }
    }
    
    public static Parser defaultParser() {
        try {
            return (Parser) Class.forName(ParserFactory.class.getPackage().getName() + 
                    ".qdox.QDoxParser").newInstance();
        } catch (Exception e) {
            throw new JavadocNgRuntimeException(e);
        }
    }
    
    public static Context parse(Configuration configuration) 
            throws ParserNotFoundException, ParseException, LoggerNotFoundException {
        Parser parser = buildParser(configuration);
        String[] directories = configuration.getSourcepath().split(
                File.pathSeparator);
        for (String directory : directories) {
            try {
                parser.addDirectory(new File(directory));
            } catch (IOException e) {
                //TODO more specific
                throw new JavadocNgRuntimeException(e);
            }
        }
        return parser.parse(configuration, LoggerFactory.buildLogger(configuration));
    }
    
    private ParserFactory() {
    }
}
